package org.apache.cordova.datetimepicker;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.LinearLayout;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;

import com.winner.forewide.R;

public class DateTimePicker extends CordovaPlugin implements OnDateChangedListener, OnTimeChangedListener {

	private DatePicker datePicker;

	private TimePicker timePicker;

	private AlertDialog ad;

	private String dateTime;

	private String initDateTime;

	private Activity activity;

	private String actionName;

	private String datetimeFormat = "yyyy-MM-dd HH:mm";

	private String dateFormat = "yyyy-MM-dd";

	private String timeFormat = "HH:mm";

	public DateTimePicker() {

	}

	public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
		if (this.cordova.getActivity().isFinishing()) {
			return true;
		}
		this.activity = cordova.getActivity();
		actionName = action;
		if (action.equals("datetimepicker")) {
			this.initDateTime = args.getString(1);
			this.datetimepicker(args.getJSONArray(0), callbackContext);
			return true;
		} else if (action.equals("datepicker")) {
			this.initDateTime = args.getString(1);
			this.datetimepicker(args.getJSONArray(0), callbackContext);
			return true;
		} else if (action.equals("timepicker")) {
			this.initDateTime = args.getString(1);
			this.datetimepicker(args.getJSONArray(0), callbackContext);
			return true;
		} else if (action.equals("yearmonthpicker")) {
			this.initDateTime = args.getString(1);
			this.datetimepicker(args.getJSONArray(0), callbackContext);
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 日期时间选择器
	 * 
	 * @param buttonLabels
	 * @param callbackContext
	 */
	public synchronized void datetimepicker(final JSONArray buttonLabels, final CallbackContext callbackContext) {
		Runnable runnable = new Runnable() {
			public void run() {
				final JSONObject result = new JSONObject();
				dateTimePicKDialog(buttonLabels, callbackContext, result);
			};
		};
		this.cordova.getActivity().runOnUiThread(runnable);
	}

	public AlertDialog dateTimePicKDialog(final JSONArray buttonLabels, final CallbackContext callbackContext,
			final JSONObject result) {
		LinearLayout dateTimeLayout = (LinearLayout) activity.getLayoutInflater().inflate(R.layout.common_datetime,
				null);
		datePicker = (DatePicker) dateTimeLayout.findViewById(R.id.datepicker);
		timePicker = (TimePicker) dateTimeLayout.findViewById(R.id.timepicker);
		if (actionName.equals("datepicker")) {
			timePicker.setVisibility(View.GONE);
		} else if (actionName.equals("timepicker")) {
			datePicker.setVisibility(View.GONE);
		} else if (actionName.equals("yearmonthpicker")) {
			((ViewGroup) ((ViewGroup) datePicker.getChildAt(0)).getChildAt(0)).getChildAt(2).setVisibility(View.GONE);
			timePicker.setVisibility(View.GONE);
		}
		timePicker.setIs24HourView(true);
		init(datePicker, timePicker);
		timePicker.setOnTimeChangedListener(this);

		try {
			ad = new AlertDialog.Builder(activity).setTitle(initDateTime).setView(dateTimeLayout).setCancelable(false)
					.setNegativeButton(buttonLabels.getString(0), new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							timePicker.requestFocus();
							datePicker.requestFocus();
							try {
								if (buttonLabels.getString(0).indexOf("確定") > -1
										|| buttonLabels.getString(0).indexOf("設置") > -1
										|| buttonLabels.getString(0).indexOf("OK") > -1) {
									result.put("datetime", dateTime);
								} else {
									result.put("datetime", "");
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
							callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
						}
					}).setPositiveButton(buttonLabels.getString(1), new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							timePicker.requestFocus();
							datePicker.requestFocus();
							try {
								if (buttonLabels.getString(1).indexOf("確定") > -1
										|| buttonLabels.getString(1).indexOf("設置") > -1
										|| buttonLabels.getString(1).indexOf("OK") > -1) {
									result.put("datetime", dateTime);
								} else {
									result.put("datetime", "");
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
							callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
						}
					}).show();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		onDateChanged(null, 0, 0, 0);
		return ad;
	}

	public void init(DatePicker datePicker, TimePicker timePicker) {
		try {
			Calendar calendar = Calendar.getInstance();
			if (!(null == initDateTime || "".equals(initDateTime))) {
				if (actionName.equals("datepicker")) {
					calendar = this.getCalendar(initDateTime, dateFormat);
				} else if (actionName.equals("timepicker")) {
					String currentDate = this.formatCalendar(calendar, dateFormat);
					calendar = this.getCalendar(currentDate + " " + initDateTime, datetimeFormat);
				} else if (actionName.equals("yearmonthpicker")) {
					calendar = this.getCalendar(initDateTime + "-01", dateFormat);
				} else {
					calendar = this.getCalendar(initDateTime, datetimeFormat);
				}
			} else {
				initDateTime = this.formatCalendar(calendar, datetimeFormat);
				if (actionName.equals("datepicker")) {
					initDateTime = this.formatCalendar(calendar, dateFormat);
				} else if (actionName.equals("yearmonthpicker")) {
					initDateTime = this.formatCalendar(calendar, dateFormat);
				} else if (actionName.equals("timepicker")) {
					initDateTime = this.formatCalendar(calendar, timeFormat);
				}
			}
			datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
					calendar.get(Calendar.DAY_OF_MONTH), this);
			timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY));
			timePicker.setCurrentMinute(calendar.get(Calendar.MINUTE));
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
		onDateChanged(null, 0, 0, 0);
	}

	public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(),
				timePicker.getCurrentHour(), timePicker.getCurrentMinute());
		SimpleDateFormat sdf = new SimpleDateFormat(datetimeFormat);
		if (actionName.equals("datepicker")) {
			sdf = new SimpleDateFormat(dateFormat);
		} else if (actionName.equals("yearmonthpicker")) {
			sdf = new SimpleDateFormat("yyyy-MM");
		} else if (actionName.equals("timepicker")) {
			sdf = new SimpleDateFormat(timeFormat);
		}
		dateTime = sdf.format(calendar.getTime());
		ad.setTitle(dateTime);
	}

	/**
	 * 将日期字符串转为日期
	 * 
	 * @param pattern
	 * @param releaseDateStr
	 * @return
	 * @throws ParseException
	 */
	public static Calendar getCalendar(String dateStr, String format) throws ParseException {
		Calendar releaseDate = null;
		DateFormat df = new SimpleDateFormat(format);
		releaseDate = new GregorianCalendar();
		releaseDate.setTime(df.parse(dateStr));
		return releaseDate;
	}

	/**
	 * 将日期转为日期字符串
	 * 
	 * @param fCal
	 * @param format
	 * @return
	 */
	private static String formatCalendar(Calendar calendar, String format) {
		if (calendar == null)
			return "";
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		return (formatter.format(calendar.getTime()));
	}
}
